package com.example.redis;

import io.netty.util.TimerTask;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@SpringBootApplication
public class RedisSampleApplication {

    @Autowired
    private RedissonClient redissonClient;

    public static void main(String[] args) {
        SpringApplication.run(RedisSampleApplication.class, args);
    }


    /**
     * 当锁已占用10s，看门狗便会触发一次锁续
     * @return
     */
    @GetMapping("/distributeLock")
    public String distributeLock(){
        String key = "key";
        RLock lock = redissonClient.getLock(key);
        try {
            //尝试获取锁，参数分别是：获取锁的最大等待时间(期间会重试)，锁自动释放时间，时间单位
            if(!lock.tryLock(5,10,TimeUnit.SECONDS)){
                String message = "线程:" + Thread.currentThread().getName() + "未获取到锁,直接返回";
                System.out.println(message);
                return message;
            }
            System.out.println("线程:" + Thread.currentThread().getName() + "获取到锁!");
            //模拟业务阻塞耗时4s
            Thread.sleep(6000);
            System.out.println("线程:" + Thread.currentThread().getName() + "业务结束!");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //判断 拿到了锁的才释放锁,否则会报错!
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                System.out.println("线程:" + Thread.currentThread().getName() + "释放锁!");
                lock.unlock();
            }
        }
        return "线程:" + Thread.currentThread().getName() + "业务结束!";
    }


}
